package main

/*
#cgo CFLAGS: -I/usr/include
#cgo LDFLAGS: -lpcre2-8
#define PCRE2_CODE_UNIT_WIDTH 8
#include <pcre2.h>
*/
import "C"
import (
	"fmt"
	"net"
	"unsafe"
)

func main() {
	// 要匹配的正则表达式
	pattern := "(?<=\\d{4})[^\\s\\d]{3,11}(?=[^\\s])"
	// PCRE2_ZERO_TERMINATED 表示模式是一个以零结尾的字符串
	pcrePattern := C.CString(pattern)
	defer C.free(unsafe.Pointer(pcrePattern))

	// 要匹配的字符串
	targetStr := "a;jhgoqoghqoj0329 u0tyu10hg0h9Y0Y9827342482y(Y0y(G)_)lajf;lqjfgqhgpqjopjqa=)*(^!@#$%^&*())9999999"
	// 将Go的字符串转换为C的字符串
	pcreTargetStr := (C.CString(targetStr))
	defer C.free(unsafe.Pointer(pcreTargetStr))

	// 错误码
	var errorcode C.int
	// 出错位置
	var erroroffset C.size_t

	// 编译正则表达式
	re := C.pcre2_compile(
		(*C.uchar)(unsafe.Pointer(pcrePattern)),
		C.PCRE2_ZERO_TERMINATED,
		0,
		&errorcode,
		&erroroffset,
		nil,
	)
	if re == nil {
		// 处理编译正则表达式的错误
		fmt.Println("PCRE2 compilation failed.")
		return
	}
	defer C.pcre2_code_free(re)

	// 创建一个匹配数据块
	matchData := C.pcre2_match_data_create_from_pattern(re, nil)
	if matchData == nil {
		fmt.Println("Cannot create match data.")
		return
	}
	defer C.pcre2_match_data_free(matchData)

	// 执行匹配
	rc := C.pcre2_match(
		re,
		(*C.uchar)(unsafe.Pointer(pcreTargetStr)),
		C.PCRE2_ZERO_TERMINATED,
		0,
		0,
		matchData,
		nil,
	)

	if rc > 0 {
		// 获取匹配结果
		ovector := (*[1 << 30]C.size_t)(unsafe.Pointer(C.pcre2_get_ovector_pointer(matchData)))
		startPos := uint32(ovector[0])
		endPos := uint32(ovector[1])
		sendUDP(targetStr[startPos:endPos])
	} else {
		fmt.Println("Matching error:", rc)
	}
}

func sendUDP(data string) {
	conn, err := net.Dial("udp", "127.0.0.1:8888")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer conn.Close()

	_, err = conn.Write([]byte(data))
	if err != nil {
		fmt.Println(err)
		return
	}
}


